package com.hsh.learning.nio.javanio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by root on 17-7-4.
 */
public class TimeServer implements Runnable {

    private Selector selector;

    public static void main(String[] args) throws Exception {
        TimeServer timeServer = new TimeServer();
        timeServer.start();
        new Thread(timeServer).start();


    }

    public void start() throws Exception {
        selector = Selector.open();
        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.socket().bind(new InetSocketAddress("127.0.0.1", 8080));
        channel.configureBlocking(false);
        SelectionKey register = channel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("time server start succ");
    }

    @Override
    public void run() {
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    handlerInput(key);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }

    private void handlerInput(SelectionKey key) throws Exception {
        if (key.isValid()) {
            if (key.isAcceptable()) {
                ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                SocketChannel sc = channel.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }

            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer buf = ByteBuffer.allocate(1024);
                int readBytes = sc.read(buf);
                if (readBytes > 0) {
                    buf.flip();
                    byte[] bytes = new byte[buf.remaining()];
                    buf.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("the time server receive order : " + body);
                    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "bade order";
                    dowrite(sc, currentTime);
                } else if (readBytes < 0) {
                    //对端链路关闭
                    key.cancel();
                    sc.close();
                } else {
                    //读到0字节,不处理
                }

            }
        }
    }

    private void dowrite(SocketChannel sc, String currentTime) throws IOException {
        if (sc != null && currentTime != null && currentTime.trim().length() > 0) {
            ByteBuffer allocate = ByteBuffer.allocate(currentTime.length());
            allocate.put(currentTime.getBytes());
            allocate.flip();
            sc.write(allocate);
        }
    }


}
